#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys

IncludePath="/var/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
#********************Setup psycopg2 and django section********************
import COOPIP_Misc

import urllib
import httplib
import datetime
import smtplib
from email.mime.text import MIMEText
        

def Get24HourMeterReport():
    StartDate = datetime.datetime.now() - datetime.timedelta(hours=24)
    EndDate = datetime.datetime.now()

    Report=[]
    if StartDate and EndDate:
        Meters=list(Meter.objects.all())
        MeterDict={}
        for i in Meters:
            MeterDict[i.SerialNumber] = i
        #Meteracctsmits=list(AMR.Meteracctsmit.objects.filter(metertccurdatetime__gte=StartDate).filter(serialnumber=55178857).order_by('serialnumber', 'metertcqualitycode', '-metertccurdatetime'))
        Meteracctsmits=list(AMR.Meteracctsmit.objects.filter(metermitreaddt__gte=StartDate).filter(metermitreaddt__lte=EndDate).order_by('-metermitreaddt'))
        Meteracctstcs=list(AMR.Meteracctstc.objects.filter(metertccurdatetime__gte=StartDate).filter(metertccurdatetime__lte=EndDate).order_by('-metertccurdatetime'))
        Metermitresponselogdatas=list(AMR.Metermitresponselogdata.objects.filter(metermitreaddt__gte=StartDate).filter(metermitreaddt__lte=EndDate).order_by('-metermitreaddt'))
        Metertcresponselogs=list(AMR.Metertcresponselog.objects.filter(metertcrespcurdatetime__gte=StartDate).filter(metertcrespcurdatetime__lte=EndDate).order_by('-metertcrespcurdatetime'))	
        RaiseString = str(len(Meteracctsmits)) + ' ' + str(len(Meteracctstcs)) + ' ' + str(len(Metermitresponselogdatas)) + ' ' + str(len(Metertcresponselogs))
        #Display List:  SerialNumber, ReadDateTime
        DisplayList = []
        QualityCodeSummary = {}
        for i in Meteracctsmits:
            try:
                SubstationName=MeterDict[str(i.serialnumber)].AMRSubstationName
                FeederName=MeterDict[str(i.serialnumber)].AMRCircuitName
                Phase=MeterDict[str(i.serialnumber)].AMRPhaseCode
            except KeyError:
                SubstationName='UNKNOWN'
                FeederName='UNKNOWN'
                Phase=''
            if not i.metermitqualitycode in [3,6]:
                DisplayList.append([i.serialnumber, i.metermitreaddt, COOPIP_Misc.CalculateQuality(i.metermitqualitycode), 'AMR', SubstationName, FeederName, Phase])
            if i.metermitqualitycode in QualityCodeSummary:
                QualityCodeSummary[i.metermitqualitycode] += 1
            else:
                QualityCodeSummary[i.metermitqualitycode] = 0
        for i in Meteracctstcs:
            try:
                SubstationName=MeterDict[str(i.serialnumber)].AMRSubstationName
                FeederName=MeterDict[str(i.serialnumber)].AMRCircuitName
                Phase=MeterDict[str(i.serialnumber)].AMRPhaseCode
            except KeyError:
                SubstationName='UNKNOWN'
                FeederName='UNKNOWN'
                Phase=''
            if not i.metertcqualitycode in [3,6]:
                DisplayList.append([i.serialnumber, i.metertccurdatetime, COOPIP_Misc.CalculateQuality(i.metertcqualitycode), 'Meter', SubstationName, FeederName, Phase])
            if i.metertcqualitycode in QualityCodeSummary:
                QualityCodeSummary[i.metertcqualitycode] += 1
            else:
                QualityCodeSummary[i.metertcqualitycode] = 0
        for i in Metermitresponselogdatas:
            try:
                SubstationName=MeterDict[str(i.serialnumber)].AMRSubstationName
                FeederName=MeterDict[str(i.serialnumber)].AMRCircuitName
                Phase=MeterDict[str(i.serialnumber)].AMRPhaseCode
            except KeyError:
                SubstationName='UNKNOWN'
                FeederName='UNKNOWN'
                Phase=''
            if not i.metermitqualitycode in [3,6]:
                DisplayList.append([i.serialnumber, i.metermitreaddt, COOPIP_Misc.CalculateQuality(i.metermitqualitycode), 'On Request', SubstationName, FeederName, Phase])
            if i.metermitqualitycode in QualityCodeSummary:
                QualityCodeSummary[i.metermitqualitycode] += 1
            else:
                QualityCodeSummary[i.metermitqualitycode] = 0
        for i in Metertcresponselogs:
            try:
                SubstationName=MeterDict[str(i.serialnumber)].AMRSubstationName
                FeederName=MeterDict[str(i.serialnumber)].AMRCircuitName
                Phase=MeterDict[str(i.serialnumber)].AMRPhaseCode
            except KeyError:
                SubstationName='UNKNOWN'
                FeederName='UNKNOWN'
                Phase=''
            if not i.metertcrespqualitycode in [3,6]:
                DisplayList.append([i.serialnumber, i.metertcrespcurdatetime, COOPIP_Misc.CalculateQuality(i.metertcrespqualitycode), 'Metertcresponselogs', SubstationName, FeederName, Phase])
            if i.metertcrespqualitycode in QualityCodeSummary:
                QualityCodeSummary[i.metertcrespqualitycode] += 1
            else:
                QualityCodeSummary[i.metertcrespqualitycode] = 0
        Report.append('Quality Code'.ljust(25) + 'Quantity')
        for i in QualityCodeSummary:
            Report.append(COOPIP_Misc.CalculateQuality(i).ljust(30) + str(QualityCodeSummary[i]))
        Report.append('')
        Report.append('')
        DisplayList.sort(key=lambda element: [element[2], element[0]]) 
        Report.append('Meter DCSI Number'.ljust(20) + 'Read Date'.ljust(25) + 'QualityCode'.ljust(30) + 'Read Type'.ljust(25) + 'Substation'.ljust(20) + 'Feeder'.ljust(20) + 'Phase'.ljust(10))
        for i in DisplayList:
            Report.append(str(i[0]).ljust(20) + str(i[1]).ljust(25) + str(i[2]).ljust(30) + str(i[3]).ljust(25) + str(i[4]).ljust(20) + str(i[5]).ljust(20) + str(i[6]).ljust(10))
            #+ str(i.metertcqualitycode).ljust(20) + str(i.metertcreadtype).ljust(10) + str(i.metertctotalconsumpt).ljust(15))
    Preformatted='\n'.join(Report)
    return (QualityCodeSummary, Preformatted)

def SendEmail(Subject='TEST', Body=''):
    Message = MIMEText(Body)
    Message['Subject']=Subject
    Message['From']='COOPIP@tce.coop'
    Message['To']='technology@tce.coop'
    Sender=smtplib.SMTP('192.168.100.8')
    Sender.sendmail('arbitrary@tce.coop', ['technology@tce.coop'], Message.as_string())
    Sender.quit()
    print 'Message sent'


AlertThreshold = 97 #percent 
SuccessCount=0
FailCount=0
QualityCodeSummary, Message = Get24HourMeterReport()
for i in QualityCodeSummary:
    if i == 3 or i == 6:
        SuccessCount += QualityCodeSummary[i]
    else:
        FailCount += QualityCodeSummary[i]

Total = SuccessCount + FailCount
SuccessPercentage = (float(SuccessCount)/float(Total)) * 100.0
#if SuccessPercentage < AlertThreshold:
#    SubjectStatus = 'Automated ALERT: Meter Reading Failure Percentage Too High'
#elif Total < 10000: #varies, but this seems reasonable.  Remove if problematic
#    SubjectStatus = 'Automated ALERT: Fewer Meter Readings than Expected: ' + str(Total)
#else:
SubjectStatus = 'Automated Notification: Meter Readings'# Acceptable'

SendEmail(Subject=SubjectStatus, Body=Message)


    
        









